package erabbit.net.camerabot;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Environment;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jph.takephoto.model.TImage;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadOptions;
import com.socks.okhttp.plus.OkHttpProxy;
import com.socks.okhttp.plus.listener.UploadListener;
import com.socks.okhttp.plus.model.Progress;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.bingoogolapple.progressbar.BGAProgressBar;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;
import erabbit.net.camerabot.utils.Auth;
import erabbit.net.camerabot.utils.StringUtils;
import okhttp3.Call;
import okhttp3.Response;

public class ShowImageActivity extends Activity {
    ArrayList<TImage> images;
    ImageView imageView;
    ImageView qrcode;
    String TAG = "ShowImageActivity";
    BGAProgressBar progressBar;
    String TOKEN = "VigPHAyVIzK_WLGiOL7ZV3x84G4il2BiECg43DJN:NaskUCf50dEnHqOxLjaSjHyPyFg=:eyJzY29wZSI6ImNhbWVyYWJvdCIsImRlYWRsaW5lIjoxNTA5MjE2MTk0fQ==";
    String URL_UPLOAD = "http://oyiyw8jtz.bkt.clouddn.com";
    String AccessKey = "VigPHAyVIzK_WLGiOL7ZV3x84G4il2BiECg43DJN";
    String SecretKey = "y9IU_pZWBW7wa3iqfChWjZi4v-h-n3KGfqCB3EA9";
    String picUrl = "";
    Handler handler = new Handler();
    TextView countdown;
    TextView tip;
    int countdownTime = 15;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_image);
        imageView = (ImageView) findViewById(R.id.imageView);
        qrcode = (ImageView) findViewById(R.id.qrcode);
        progressBar = (BGAProgressBar) findViewById(R.id.progressBar);
        countdown = (TextView) findViewById(R.id.countdown);
        tip = (TextView) findViewById(R.id.tip);

        images = (ArrayList<TImage>) getIntent().getSerializableExtra("images");
        picUrl = getIntent().getStringExtra("picUrl");
        TOKEN = Auth.create(AccessKey, SecretKey).uploadToken("camerabot");
        showImg();
        if (MyApplication.bmp != null) {
            imageView.setImageBitmap(MyApplication.bmp);
        }

        countdown.setVisibility(View.GONE);
        tip.setVisibility(View.GONE);

    }

    private void showImg() {
        if (images != null && images.size() > 0) {
            Log.i("ShowImageActivity=", images.get(0).getOriginalPath());
            Glide.with(this).load(new File(images.get(0).getOriginalPath())).into(imageView);
        }
        Log.i(TAG, "picUrl=" + picUrl);
        if (!StringUtils.isEmpty(picUrl)) {
            Log.i(TAG, "开始上传数据");
            qnUpLoad();
        }
    }


    /**
     * 采用七牛上传接口，Token有效期为12小时，若Token无效，请在下面自行获取
     * Token生成网址 http://jsfiddle.net/gh/get/extjs/4.2/icattlecoder/jsfiddle/tree/master/uptoken
     * <p/>
     * AK = IUy4JnOZHP6o-rx9QsGLf9jMTAKfRkL07gNssIDA
     * CK = DkfA7gPTNy1k4HWnQynra3qAZhrzp-wmSs15vub6
     * BUCKE_NAME = zhaokaiqiang
     */
    public void uploadFile() {

        File file = new File(picUrl);
        if (!file.exists()) {
            Toast.makeText(ShowImageActivity.this, "文件不存在，请修改文件路径", Toast.LENGTH_SHORT).show();
            return;
        }

        Map<String, String> param = new HashMap<>();
        param.put("token", TOKEN);
        Pair<String, File> pair = new Pair("file", file);

        OkHttpProxy
                .upload()
                .url(URL_UPLOAD)
                .file(pair)
                .setParams(param)
                .setWriteTimeOut(20)
                .start(new UploadListener() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d(TAG, e.getMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.d(TAG, "isSuccessful = " + response.isSuccessful() + "\n" + "code = " + response.code());
                    }

                    @Override
                    public void onSuccess(Response response) {
                        Log.d(TAG, "isSuccessful = " + response.isSuccessful() + "\n" + "code = " + response.code());
                    }

                    @Override
                    public void onFailure(Exception e) {
                        Log.d(TAG, e.getMessage());

                    }

                    @Override
                    public void onUIProgress(Progress progress) {
                        int pro = (int) ((progress.getCurrentBytes() + 0.0) / progress.getTotalBytes() * 100);
                        if (pro > 0) {
                            progressBar.setProgress(pro);
                        }
                        Log.d(TAG, "pro = " + pro + " getCurrentBytes = " + progress.getCurrentBytes() + " getTotalBytes = " + progress.getTotalBytes());
                    }

                });
    }


    private void qnUpLoad() {

        File file = new File(picUrl);
        if (!file.exists()) {
            Toast.makeText(ShowImageActivity.this, "文件不存在，请修改文件路径", Toast.LENGTH_SHORT).show();
            return;
        }

        MyApplication.uploadManager.put(file, null, TOKEN,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        if (info.isOK()) {
                            progressBar.setVisibility(View.GONE);
                            Log.i(TAG, "Upload Success");

                            String url = "http://oyiyw8jtz.bkt.clouddn.com/" + res.optString("key");

                            qrcode.setImageBitmap(QRCodeEncoder.syncEncodeQRCode(url, 200, Color.parseColor("#00FFFF"), MyApplication.bmp));

                            countdown.setVisibility(View.VISIBLE);
                            tip.setVisibility(View.VISIBLE);
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    countdown.setVisibility(View.VISIBLE);
                                    countdown.setText(String.valueOf(countdownTime));
                                    tip.setText("扫描二维码下载图片，" + countdownTime + "秒后自动返回");

                                    countdownTime--;
                                    String text = tip.getText().toString();
                                    SpannableString mSpannableString = new SpannableString(text);
                                    ForegroundColorSpan fcs = new ForegroundColorSpan(Color.parseColor("#FF0000"));
                                    int flag = Spanned.SPAN_INCLUSIVE_EXCLUSIVE;
                                    mSpannableString.setSpan(fcs, text.indexOf("，")+1, text.indexOf("秒"), flag);
                                    tip.setText(mSpannableString);


                                    if (countdownTime == 0) {
                                        onBackPressed();
                                    } else {
                                        handler.postDelayed(this, 1000 * 1);
                                    }
                                }
                            }, 0); //每隔1s执行


                        } else {
                            Log.i(TAG, "Upload Fail");
                            //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                        }
                        Log.i(TAG, key + ",\r\n " + info + ",\r\n " + res);
                    }
                }, new UploadOptions(null, null, false,
                        new UpProgressHandler() {
                            public void progress(String key, double percent) {
                                Log.i(TAG, key + ": " + percent);
                                progressBar.setProgress((int) (percent * 100));

                            }
                        }, null));
    }


}
